package ua.com.softway.mail;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Will notify mail thread, that new message are available
 * Should be placed around transaction filter
 */
public class NotifyMailerFilter implements Filter {

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        
        try {
            notify.set(null);
            
            chain.doFilter(request, response);
        } finally {
            if (notify.get() != null)
                Mailer.notifyMailer();
        }
    }

    private static ThreadLocal<Boolean> notify = new ThreadLocal<Boolean>();
    
    static void notifyMailer() {
        notify.set(true);
    }
}
